<!--
 * @Author: wangshuguang
 * @Date: 2022-02-22 14:40:28
 * @LastEditTime: 2022-10-18 18:12:58
 * @LastEditors: wangshuguang
 * @Description: 充值流量余额
-->

<template>
  <div class="recharge">
    <HeaderComp title="充值流量余额" />
    <div class="title">选择充值金额</div>
	<van-loading size="24px" vertical v-show="pageLoading">加载中...</van-loading>
    <!-- 套餐列表 -->
    <div class="mealList">
      <div 
      v-for="mealItem of mealList" 
      :key="mealItem.m" 
      :class="`mealItem ${nowMeal.id == mealItem.id ? 'mealActive' : ''}`" 
      @click="changeMeal(mealItem)">
        <div class="mealItem-div_money">{{ mealItem.money }}元</div>
        <img class="mealItem-div_arrow" src="../../assets/img/flow/arrow.png" alt="">
		
      </div>
	  <div class="mealItem" style="background-color: #fff;"></div>
	 
	 
    </div>
	
    <div class="labelText">
      可获得<span class="">{{ nowMeal.money }}流量余额</span>
    </div>
    <div class="payLabel">支付方式</div>
    <div >
        <van-radio-group v-model="form.payType">
          <div class="payType">
            <van-radio name="WALL" checked-color="#FFB72F" icon-size="24px" :disabled="canWallPay"/>
            <div class="payTypeContent">
              钱包余额（剩余￥{{accountBal}}）
              <div class="balanceLabel" v-if="form.payAmount && accountBal < nowMeal.money">余额不足，请先充值</div>
            </div>
            <!-- <div class="btn" @click="showRecharge">去充值</div> -->
          </div>
          <div class="payType mg-t-20">
            <van-radio name="ZFB" checked-color="#FFB72F" icon-size="24px"/>
            <div class="payTypeContent">
              支付宝支付
            </div>
          </div>
        </van-radio-group>
    </div>
    <div class="submitBtn" @click="submit" :loading="btnLoading">确定</div>

    
    <!-- 充值弹框 -->
    <van-dialog 
      v-model="rechargeVisible" 
      round 
      position="bottom" 
      show-cancel-button
      confirmButtonText="保存至相册" 
      :before-close="qrCodeClose"
      className="rechargeDialog">
      <div class="rechargeTitle">充值钱包余额</div>
      <div ref="qrCode" class="qrCode" v-if="rechargeVisible"></div>
      <div class="qrcodeLabel">说明：请截屏或保存二维码至本地相册， 并使用微信/支付宝扫一扫进行扫码支付</div>
    </van-dialog>
    <!-- 选择金额 -->
    <van-dialog 
      className="rechargePwdDialog"
      v-model="pwdVisible" 
      show-cancel-button 
      :before-close="pwdClose">
      <div class="info">
        <div class="closeIcon"></div>
        <div class="title">请输入支付密码</div>
        <div class="money">￥{{nowMeal.money}}</div>
        <div class="payTypeLabel">
          <span>支付方式</span>
          <span>钱包余额</span>
        </div>
      </div>
      <van-password-input
        :value="form.pwd"
        :focused="showKeyboard"
        @focus="showKeyboard = true"
      />
    </van-dialog>
    <!-- 数字键盘 -->
    <van-number-keyboard
      z-index="3000"
      v-model="form.pwd"
      :show="showKeyboard"
      @blur="showKeyboard = false"
    />
  </div>
</template>

<script>

import { 
  queryEnjoyAccountBalance,
  getOpenAmount,
  rechargeAmount,
  openEnjoyFavour,
  createPayAmountQrCode,
  wapAliPay,
  checkUpFlowBalance
} from "@/api/flow/index";
import { mapGetters } from "vuex";
import QRCode from '@keeex/qrcodejs-kx'
import { savePicture, payFormSubmit } from "@/utils/utils";
export default {
  data(){
    return{
      rechargeVisible: false,
      pwdVisible: false,
      showKeyboard: false,
      form:{
        payType:'WALL',
        payAmount: 0,
        pwd:''
      },
      qrCodeObj: null,
      btnLoading: false,
      nowMeal:{},
      money: 300,
      accountBal: 0,
      mealList:[],
	  pageLoading:false,
    }
  },
  computed:{
    canWallPay(){
      return this.accountBal < this.nowMeal.money
    },
    ...mapGetters(['flowQueryData'])
  },
  mounted(){
    this.getBaseData()
  },
  methods:{
    getBaseData(){
		this.pageLoading = true
      const { merchantId,deptId } = this.flowQueryData
      queryEnjoyAccountBalance({
        deptId,
        merchantId,
        userType :'merch'
      }).then(res => {
		  this.pageLoading = false
        console.log('res',res)
        this.accountBal = res.data.data || 0
      })
      getOpenAmount({deptId}).then(res => {
		  this.pageLoading = false
        this.mealList = res.data.data.map((item, index) => {
          return {
            ...item,
            id: 'money'+index,
            money: item.rechargeFixMoney
          }
        })
      })
    },
    submit(){
      const { merchantId } = this.flowQueryData
      console.log('submit')
      if(!this.nowMeal.money){
        this.$toast('请选择充值金额')
        return 
      }else if(!this.form.payType){
        this.$toast('请选择支付方式')
        return 
      }
      checkUpFlowBalance({
        payFlowBalance: this.nowMeal.money,
        payee : merchantId,
        pkgId : this.nowMeal.pkgId,
        payType: this.form.payType
      }).then(res => {
        const { data, msg } = res.data
        if(data){
          if(this.form.payType == 'WALL'){
            if(this.nowMeal.money > this.accountBal ){
              this.$toast('钱包余额不足，请切换支付方式！')
              return
            } 
            this.pwdVisible = true
          }else{
            this.zfbPay(data)
          }
        }else{
          this.$toast(msg)
        }
      })
    },
    zfbPay(checkData){
      
        const { merchantId,deptId,agentId,merchantNo, shopId,merchantFullName } = this.flowQueryData
        const { payType,payAmount } = this.form
        const calcMealData = {
          comboTotalCost:'',
          surplusFlow:'',
          shopCount:'',
          manyShopCost:'',
        }
            let submitInfo = {}
            
            // 支付宝支付
            let obj = {
              agentId,
              openFlag: 0,
              upUserId: checkData.upUserId,
              upUserType: checkData.upUserType,
              routing:'rechargeResult',
              quitRouting:`rechargeResult?payType=ZFBERR`,
              autoBusinessNo: submitInfo.autoBusinessNo,
              businessNo: submitInfo.businessNo,
              "comboBaseCost": this.nowMeal.money,
              "comboTotalCost": calcMealData.comboTotalCost,
              dedBusinessNo: submitInfo.dedBusinessNo,
              deptId,
              "manyShopCost": calcMealData.manyShopCost,
              merchantFullName,
              merchantId,
              merchantNo,
              "payFlowBalance": this.nowMeal.money,
              "payType": this.form.payType,
              "pkgId" : this.nowMeal.money,
              "shopCount": calcMealData.shopCount,
              "subject": '充值流量余额',
              "surplusFlow": calcMealData.surplusFlow,
              "totalAmount": this.nowMeal.money,
            }
            wapAliPay(obj).then(res => {
              console.log('res',res)
              payFormSubmit(res.data.data)
            })
    },
    pwdClose(type,done){
      if(type == 'confirm'){
        const { merchantId,deptId } = this.flowQueryData
        // this.$router.push('rechargeResult')
        let obj = {
          merchantId,
          payFlowBalance: this.nowMeal.money,
          deptId,
          changeAmount: this.nowMeal.money,
          payType: this.form.payType,
          comboTotalCost: this.nowMeal.money,
          payPassword: this.form.pwd,
        }
        if(!obj.payPassword){
          this.$toast('请输入密码')
          done(false)
        }else if(obj.payPassword.length < 6){
          this.$toast('请输入完整的6位密码')
          done(false)
        }else{
          rechargeAmount(obj).then(res => {
            console.log('res',res)
            const {data,code,msg}  =res.data
            if(code == 0){
              // this.$toast('支付成功')
              this.$router.push({
                path:'/rechargeResult',
                query:{ ...data }
              })
            }else{
              this.$$toast(msg)
            }
          })
        }
        
      }else{
        this.form.pwd = ''
        done()
      }
    },
    changeMeal(item){
      this.nowMeal = item
      // 如果超出钱包剩余金额  切换支付方式
      if(this.accountBal < this.nowMeal.money && this.form.payType == 'WALL'){
        this.form.payType = 'ZFB'
      }
    },
    // 二维码关闭
    qrCodeClose(type,done){
      if(type == 'confirm'){
        console.log('qrcode',this.qrCodeObj)
        const { _oDrawing } = this.qrCodeObj
        savePicture(_oDrawing._elImage.currentSrc)
        this.$toast('保存成功')
        done(false)
      }else{
        done()
      }
    },
    showRecharge(){
      const { merchantId,deptId,agentId } = this.flowQueryData
      const { payType } = this.form
      if(!this.nowMeal.money){
        this.$toast('请选择充值金额！')
        return
      }

      let obj = {
        agentId,deptId ,
        payAmount : this.nowMeal.money,
        payType  : payType,
        userId  : merchantId,
        userType :'merch'
      }
      createPayAmountQrCode(obj).then(res => {
        console.log('res',res)
        if(res.data.code == 0){
          this.rechargeVisible = true
          this.$nextTick(() => {
            this.qrCodeObj = new QRCode(this.$refs.qrCode, {
                text: res.data.data, // 需要转换为二维码的内容
                width: 354,
                height: 354,
                colorDark: '#000000',
                colorLight: '#ffffff',
            })
            console.log('qrCodeObj',this.qrCodeObj)
          })
        }
      })
    },
  }
}
</script>

<style lang='less'>

.rechargePwdDialog{
  top: 30%;
  .info{
    padding: 20px;
    .title{
      font-size: 32px;
      color: #131313;
      text-align: center;
    }
    .money{
      font-size: 60px;
      color: #131313;
      text-align: center;
      margin-bottom: 67px;
    }
    .payTypeLabel{
      display: flex;
      justify-content: space-between;
      color: #131313;
      opacity: 0.7;
      margin-bottom: 60px;
    }
  }
}
.rechargeDialog{
  .van-dialog__footer{
    .van-dialog__cancel{
      color: #FFB72F;
    }
    .van-dialog__confirm{
      background: #FFB72F;
      color: #fff;
    }
  }
  .van-dialog__content{
    padding: 20px;
    text-align: center;
    .rechargeTitle{
      color: #131313;
      font-size: 34px;
    }
    .qrCode{
      margin: 40px 0;
      padding: 0 70px;
      img{
        width: 100%;
      }
    }
  }
}
.recharge{
  padding: 30px;
  .title{
    color: #131313;
    font-size: 32px;
    font-weight: bold;
  }
  .mealList{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 30px 0 0;
    height: 370px;
    overflow: auto;
    .mealItem{
      width: 212px;
      background: #F8F8F8;
      border-radius: 15px;
      padding: 40px 0;
      flex-shrink: 0;
      font-size: 36px;
      position: relative;
      margin-bottom: 30px;
      .mealItem-div_money{
        text-align: center;
      }
      .mealItem-div_arrow{
        position: absolute;
        top: 0;
        right: 0;
        display: none;
        width: 64px;
      }
      &.mealActive{
        background: #FFB72F;
        color: #fff;
        .mealItem-div_arrow{
          display: inline-block;
        }
      }
    }
  }
  .labelText{
    font-size: 32px;
    margin-top: 20px;
    span{
      color: #FFB72F;
      margin-left: 10px;
    }
  }
  // .payType{
  //   margin-top: 80px;
  //   .label{
  //     font-size: 32px;
  //     color: #131313;
  //     font-weight: bold;
  //     margin-bottom: 30px;
  //   }
  //   .payTypeContent{
  //     display: flex;
  //     justify-content: space-between;
  //     .left{
  //       font-size: 32px;
  //       display: flex;
  //       font-weight: bold;
  //       .money{
  //         margin-left: 10px;
  //         opacity: 0.6;
  //         .warnTip{
  //           color: #F05357;
  //           font-size: 28px;
  //           margin-top: 14px;
  //         }
  //       }
  //     }
  //     .btn{
  //       font-size: 28px;
  //       color: #fff;
  //       background: #FFB72F;
  //       border-radius: 27px;
  //       width: 130px;
  //       line-height: 54px;
  //       height: 54px;
  //       text-align: center;
  //     }
  //   }
  // }
  .payLabel{
    font-size: 32px;
    font-weight: bold;
    margin-top: 98px;
  }
  .payType{
    display: flex;
    margin-top: 10px;
    .payTypeContent{
      font-size: 32px;
      margin-left: 20px;
      flex: 1;
      .balanceLabel{
        color: #F05357;
        font-size: 28px;
      }
    }
    .btn{
      font-size: 28px;
      color: #fff;
      background: #FFB72F;
      border-radius: 27px;
      width: 130px;
      line-height: 54px;
      height: 54px;
      text-align: center;
    }
  }
  .submitBtn{
    position: absolute;
    bottom: 30px;
    left: 50%;
    transform: translate(-50%, 0);
    background: #FFB72F;
    border-radius: 40px;
    width: calc(100% - 150px);
    text-align: center;
    height: 80px;
    line-height: 80px;
    font-size: 32px;
    color: #fff;
  }
}
</style>